package com.gmscosmo.janus.echarts;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gmscosmo.janus.config.JanusConfig;
import com.gmscosmo.janus.util.JanusUtil;
import com.gmscosmo.model.Node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@RestController
public class EchartsController {
    private static final String PREFIX_MAX_PARTICIPANT = "MAX_PARTICIPANT";
    private static final String PREFIX_IS_SHARE_STREAM = "IS_SHARE_STREAM";
    private static final String PREFIX_LOAD_DISTRIBUTION_STRATEGY = "LOAD_DISTRIBUTION_STRATEGY";
    @Autowired
    JanusConfig janusConfig;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    RedisClusterPoolUtilForEcharts redisClusterPoolUtilForEcharts;
    @Autowired
    JanusUtil janusUtil;

    @GetMapping("/getOption")
    public String getOption() {
        HashMap<Integer, String> janusNodeHostMap = new HashMap<>(16);
        HashMap<String, Point> janusServerNodes = new HashMap<>(16);
        HashMap<String, Point> interJanusServerNodes = new HashMap<>(16);
        HashMap<String, Point> roomNodes = new HashMap<>(16);
        HashMap<String, Point> participantNodes = new HashMap<>(16);
        List<Link> links = new ArrayList<>();
        int serverNum = redisClusterPoolUtilForEcharts.getJanusServerNum(janusNodeHostMap, janusServerNodes, interJanusServerNodes);
//        System.out.println("当前多人音视频服务器数量:" + serverNum);
        redisClusterPoolUtilForEcharts.getRoomNum(roomNodes);
//        System.out.println("当前多人音视频房间数量:" + redisClusterPoolUtil.getRoomNum(roomNodes));
        int participants = redisClusterPoolUtilForEcharts.getParticipantNum(janusNodeHostMap, links, janusServerNodes, participantNodes);
//        System.out.println("当前多人音视频总人数:" + participants);
//        System.out.println("当前多人音视频端口占用数量:" + redisClusterPoolUtil.getPortNum());
        redisClusterPoolUtilForEcharts.getRtpForwardData(links, janusServerNodes, interJanusServerNodes);
        int x = 0;
        int y = 0;
        int i = 0;
        for (Point janus : janusServerNodes.values()) {
            if (i % 4 == 0) {
                y += 300;
                x = 0;
            }
            janus.setX(x);
            x += 300;
            janus.setY(y);
            i++;
        }
        x = 0;
        i = 0;
        int roomSize = 50 + 300 / (1 + roomNodes.size());
        for (Point room : roomNodes.values()) {
            if (i % 4 == 0) {
                y += 300;
                x = 0;
            }
            room.setX(x);
            x += 300;
            room.setY(y);
            i++;
            room.setSymbolSize(roomSize);
        }
        redisClusterPoolUtilForEcharts.getParticipantRoom(roomNodes, participantNodes);
        Option option = new Option();
        Title title = new Title();
        title.setText("多人音视频");
        option.setTitle(title);
        Series series = new Series();
        series.setLabel(new Label());
        series.setEdgeLabel(new EdgeLabel());
        List<Point> data = new ArrayList<>();
        data.addAll(janusServerNodes.values());
        data.addAll(roomNodes.values());
        data.addAll(participantNodes.values());
        series.setData(data);
        series.setLinks(links);

        LineStyle lineStyle = new LineStyle();
        lineStyle.setCurveness(0.2);
        lineStyle.setWidth(2);
        series.setLineStyle(lineStyle);
        option.setSeries(series);
        return JSON.parse(option.toString()).toString();
    }

    @GetMapping("/getMaxParticipant")
    public int getMaxParticipant() {
        String object = redisTemplate.opsForValue().get(PREFIX_MAX_PARTICIPANT + "");
        int num = object == null ? 0 : JSONObject.parseObject(object, Integer.class);
        return num;
    }

    @GetMapping("/putMaxParticipant/{num}")
    public void putMaxParticipant(@PathVariable("num") int num) {
        redisTemplate.opsForValue().set(PREFIX_MAX_PARTICIPANT + "", String.valueOf(num));
    }

    @GetMapping("/getLoadDistributionStrategy")
    public int getLoadDistributionStrategy() {
        String object = redisTemplate.opsForValue().get(PREFIX_LOAD_DISTRIBUTION_STRATEGY + "");
        int num = object == null ? 0 : JSONObject.parseObject(object, Integer.class);
        return num;
    }

    @GetMapping("/putLoadDistributionStrategy/{num}")
    public void putLoadDistributionStrategy(@PathVariable("num") int num) {
        redisTemplate.opsForValue().set(PREFIX_LOAD_DISTRIBUTION_STRATEGY + "", String.valueOf(num));
    }

    @GetMapping("/getIsShareStream")
    public boolean getIsShareStream() {
        String object = redisTemplate.opsForValue().get(PREFIX_IS_SHARE_STREAM + "");
        boolean isShareStream = object == null ? false : JSONObject.parseObject(object, Boolean.class);
        return isShareStream;
    }


    @GetMapping("/putIsShareStream/{isShareStream}")
    public void putIsShareStream(@PathVariable("isShareStream") boolean isShareStream) {
        redisTemplate.opsForValue().set(PREFIX_IS_SHARE_STREAM + "", String.valueOf(isShareStream));
    }

    @GetMapping("/getRedis/{del}")
    public void getRedis(@PathVariable("del") int del) {
        ArrayList<String> lists = new ArrayList(Arrays.asList("MAX_PARTICIPANT", "LOAD_DISTRIBUTION_STRATEGY", "SUBSCRIBERS", "PRODUCERS", "USER_NODE", "NODE_INFO", "ROOM_NODEID", "USER_ROOM", "ROOM_INFO", "PORT", "PUBLISH"));
        for (String str : lists) {
            redisClusterPoolUtilForEcharts.getRedis(str, del == 1);
        }
    }


    @PostMapping("/addNode")
    public boolean addNode(@RequestBody Node node) {
        if (janusUtil.getNodeInfos().containsValue(node)) {
            return false;
        }
        node.setNodeId(janusUtil.getNodeInfos().size());
        node.setParticipant(0);
        janusUtil.putNodeInfo(node.getNodeId(), node);
        return true;
    }

    @PostMapping("/updateNode")
    public boolean updateNode(@RequestBody Node node) {
        if (janusUtil.getNodeInfos().containsValue(node)) {
            return false;
        }
        janusUtil.updateNodeInfo(node.getNodeId(), node);
        return true;
    }


    @GetMapping("/deleteNode/{del}")
    public void deleteNode(@PathVariable("del") int del) {
        janusUtil.removeNodeInfo(del);
    }

    @GetMapping("/getNodeInfo/{id}")
    public Node getNodeInfo(@PathVariable("id") int id) {
        return janusUtil.getNodeInfo(id);
    }

    @GetMapping("/test")
    public void test(){
        try {
            int node = janusUtil.getFreeNode("123");
            System.out.println(node);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/getLogLevel")
    public int getLogLevel() {
        return janusConfig.getLog_level();
    }

    @GetMapping("/putLogLevel/{num}")
    public void putLogLevel(@PathVariable("num") int num) {
        janusConfig.setLog_level(num);
    }


    @GetMapping("/getIsLog")
    public boolean getIsLog() {
        return janusConfig.isIs_log();
    }

    @GetMapping("/putIsLog/{num}")
    public void putIsLog(@PathVariable("num") boolean num) {
        janusConfig.setIs_log(num);
    }
}
